import { computed } from 'vue'
import { useLink } from './use-link'

/** uni app 路由映射 */
let routerMap: Record<string, string> = {}
let tabBarMap: Record<string, string> = {}
type routerKey = keyof typeof routerMap

interface IRouterParams {
  query?: Record<string, string>
}

// type routerName = Pick<typeof routerMap, routerKey>;
/** uni app router */
export function useRouter() {
  const link = useLink()

  const init = (map: Record<string, string>, tab: Record<string, string>) => {
    routerMap = map
    tabBarMap = tab || {}
  }

  const routeUrl = (name: routerKey, options?: IRouterParams) => {
    let url = routerMap[name]

    if (options?.query) {
      url = link.assembleLink(url, options.query)
    }

    return url
  }

  const push = (name: routerKey, options?: IRouterParams) => {
    const url = routeUrl(name, options)

    uni.navigateTo({
      url,
    })
    // uni.redirectTo({
    //   url,
    // });
  }

  const switchTab = (name: routerKey, options?: IRouterParams) => {
    const url = routeUrl(name, options)

    uni.switchTab({
      url,
    })
    // uni.redirectTo({
    //   url,
    // });
  }

  const goBack = () => {
    uni.navigateBack()
  }

  const redirect = (name: routerKey, options?: IRouterParams) => {
    const url = routeUrl(name, options)

    uni.redirectTo({
      url,
    })
  }

  const currentRouter = computed(() => {
    const pages = getCurrentPages()
    const page = pages[pages.length - 1]
    return page
  })

  const getRoute = (pageNum = 0) => {
    let pages = getCurrentPages() // 所有路由
    let pageIndex = pages.length - 1 - pageNum
    const { route = '', $page } = (pages[pageIndex] as any) || {}
    const { fullPath } = $page || {}
    const path = `/${route}`
    let title = path
    let name = getRouteName(path)

    return {
      /** 路由名称 */
      name,
      /** 页面地址 */
      path,
      /** 完整地址 */
      fullPath,
      /** 页面标题，取不到值时默认取地址 */
      title,
    }
  }

  /**
   * 获取路由名
   * @param path 路由地址
   * @returns 路由名
   */
  const getRouteName = (path: string) => {
    let name = ''

    Object.entries(routerMap).every(([key, value]) => {
      if (path === value) {
        name = key
        return false
      }

      return true
    })

    return name
  }

  const getIsTabbar = (path?: string) => {
    if (!Object.keys(tabBarMap).length) return true

    const _r: any = getCurrentPages()
    const currentPath = path || _r.at(-1).route

    return !!tabBarMap[currentPath]
  }
  return {
    init,
    push,
    goBack,
    redirect,
    routeUrl,
    routerMap,
    getRoute,
    switchTab,
    currentRouter,
    getRouteName,
    getIsTabbar,
  }
}
